import { BASE_URL, TIMEOUT } from './config.js'

import { getUserInfo } from './api.js'

export function request(options) {	
	const token = uni.getStorageSync("token");
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: "加载中...",
		})
		return uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'get',
			timeout: TIMEOUT,
			data: options.data || {},
			header: {
				"Authorization": `Bearer ${token}`,
			},
			success: (res) => {
				if(token) {
					resolve(res)
				} else {
					setTimeout(() =>{
						uni.switchTab({
							url: "/pages/profile/profile"
						})
					}, 1000)
					uni.showToast({
						title: "请先授权",
						duration: 2000,
						icon: "error"
					})
				}
			},
			fail: (err) => {
				reject(err)
			},
			complete: () => {
				uni.hideLoading();
			}
		})
	}).then(res => {
		return res.data;
	}).catch(err => {
		return err;
	})
}

export function login() {
	return new Promise((resolve, reject) => {
		return uni.request({
			url: BASE_URL + '/oauth/token',
			method: "POST",
			data: {
				username: "admin",
				password: "123456",
				scope: "ui",
				grant_type: "password",
				client_id: "browser"
			},
			header: {
				"Authorization": "Basic YnJvd3NlcjoxMjM0NTY=",
				"Content-Type": "application/x-www-form-urlencoded"
			},
			success: (res) => {
				uni.setStorageSync("token", res.data.access_token);
				
				getUserInfo().then(({data}) => {
					uni.setStorageSync("userInfo", data);
				})
				
				return resolve(res)
			},
			fail: reject
		})
	})
}

export function formdataRequest(options) {
	const token = uni.getStorageSync("token");
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: "加载中...",
		})
		return uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'get',
			timeout: TIMEOUT,
			data: options.data || {},
			header: {
				"Content-Type": "application/x-www-form-urlencoded",
				"Authorization": `Bearer ${token}`
			},
			success: (res) => {
				resolve(res)
			},
			fail: (err) => {
				reject(err)
			},
			complete: () => {
				uni.hideLoading();
			}
		})
	}).then(res => {
		return res.data;
	}).catch(err => {
		return err;
	})
}

//拦截器
// uni.addInterceptor('request', {
// 	invoke(args) {
// 		if(token) {
// 			args.header.Authorization = `Bearer ${token}`
// 		}
// 	}
// })